package com.egao.texasHoldEmPoker.service.impl;

import com.egao.common.core.damon.results.PageResult2;
import com.egao.common.core.damon.utils.Utils;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
//import com.egao.texasHoldEmPoker.mapper.DeskMapper;
import com.egao.texasHoldEmPoker.biz.PlayerBiz;
import com.egao.texasHoldEmPoker.biz.PlayerJetonBiz;
import com.egao.texasHoldEmPoker.entity.Desk;
import com.egao.texasHoldEmPoker.entity.Player;
import com.egao.texasHoldEmPoker.entity.PlayerJeton;
import com.egao.texasHoldEmPoker.entity.Poker;
import com.egao.texasHoldEmPoker.service.DeskService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import com.egao.texasHoldEmPoker.biz.DeskBiz;
import net.sf.json.JSONObject;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
//import javax.transaction.Transactional;
import org.springframework.transaction.annotation.Transactional;


import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 赌桌服务实现类
 * @author : Doman
 * @date : 2022-01-26 12:39:26
 * @version ：1.0
 */
@Service
public class DeskServiceImpl /*extends ServiceImpl<DeskMapper, Desk> */implements DeskService {

    @Autowired
    private DeskBiz deskBiz;
    @Autowired
    private PlayerBiz playerBiz;
    @Autowired
    private PlayerJetonBiz playerJetonBiz;

    public static void main(String[] args) {
//        String poker = ",,,创建房间:阿来1筹码:10";
//        String pattern = "^,,,.*";
//        boolean isMatch = Pattern.matches(pattern, poker);
//        pattern = ".*筹码:.*";
//        isMatch = Pattern.matches(pattern, poker);
//
//        System.out.println(isMatch);
//
//        String desk = "";
//        String jeton = "20";
//        if (isMatch) {
//            pattern = "^,,,创建房间:.*";
//            isMatch = Pattern.matches(pattern, poker);
//            //创建房间
//            if (isMatch) {
//                pattern = ".*筹码:.*";
//                isMatch = Pattern.matches(pattern, poker);
//                if (isMatch) {
//                    desk = poker.substring(8,poker.indexOf("筹码:"));
//                    jeton = poker.substring(poker.indexOf("筹码:"));
//                } else {
//                    desk = poker.substring(8);
//                }
//            }
//
//        }
//        int total = 8;
//        Set<Integer> hashSet = new HashSet<Integer>();
//        Random rm = new Random(1);
//        Long begin = System.currentTimeMillis();
//
//
//        List<Integer> list = new ArrayList<Integer>();
//        while (hashSet.size() != total) {
//            int a = rm.nextInt(total) + 1;
//            if (!hashSet.contains(a)) {
//                hashSet.add(a);
//                list.add(a);
//            }
//        }
////        Iterator it = hashSet.iterator();
////        while (it.hasNext()) {
////            System.out.println(it.next());
////        }
//        for (Integer c : list) {
//            System.out.println(c);
//        }
//        Long end = System.currentTimeMillis();
//        System.out.println("花费的总时间" + (end - begin));

//        Random random = new Random();
//        System.out.println("---"+random.nextInt(3));
        List<Poker> pokers = new ArrayList<>();
        Poker poker1 = new Poker();
        poker1.setName("a");
        poker1.setColors("1");
        pokers.add(poker1);
        poker1 = new Poker();
        poker1.setName("b");
        poker1.setColors("2");
        pokers.add(poker1);
        poker1 = new Poker();
        poker1.setName("c");
        poker1.setColors("3");
        pokers.add(poker1);
        poker1 = new Poker();
        poker1.setName("d");
        poker1.setColors("4");
        pokers.add(poker1);

        pokers.remove(poker1);
        System.out.println(1);
    }

    /*
    desk_code: 房间号
    msg: 消息
    players: 玩家集合
    desk: 赌桌情况
     */
    @Override
    @Transactional
    public JsonResult texasHoldEmPoker(String poker) {
        //,,,创建:阿来1筹码:10
        //,,,加入:2wechat_name:Lin.wechat_code:121
        //,,,离席:2wechat_name:Lin.wechat_code:fqwe
        //,,,加码:2wechat_name:Lin.wechat_code:333
        //,,,发牌:2
        //#:1jeton:1.1wechat_name:Lin.wechat_code:333 //下注
        String pattern = "^,,,.*";
        boolean isMatch = Pattern.matches(pattern, poker);

        JsonResult jsonResult = JsonResult.ok();
        try {
            //正确语句
            if (isMatch) {

                //创建房间
                pattern = "^,,,创建:.*";
                isMatch = Pattern.matches(pattern, poker);
                if (isMatch) {
                    createDesk(poker, jsonResult);
                }

                //玩家加入房间
                pattern = "^,,,加入:.*";
                isMatch = Pattern.matches(pattern, poker);
                if (isMatch) {
                    joinDesk(poker, jsonResult);
                }

                //加码
                pattern = "^,,,加码:.*";
                isMatch = Pattern.matches(pattern, poker);
                if (isMatch) {
                    increasePosition(poker, jsonResult);
                }

                //发牌
                pattern = "^,,,发牌:.*";
                isMatch = Pattern.matches(pattern, poker);
                if (isMatch) {
                    playCards(poker, jsonResult);
                }
            }
        } catch (Exception e) {
            jsonResult.setMsg("请联系lin. 或者检查自己输入的");
        }
        return jsonResult;
    }

    //创建房间
    private void createDesk(String poker, JsonResult jsonResult) {
        Desk desk = new Desk();
        String pattern = ".*筹码:.*";
        boolean isMatch = Pattern.matches(pattern, poker);
        if (isMatch) {
            desk.setName(poker.substring(6, poker.indexOf("筹码:")));
            desk.setIncreasePosition(Integer.valueOf(poker.substring(poker.indexOf("筹码:")+3)));
        } else {
            desk.setName(poker.substring(6));
            desk.setBlind(0);
        }
        try {
            int id = deskBiz.save(desk, new User(1));
            jsonResult.setMsg("房间:"+desk.getName()+" 创建成功");
            jsonResult.put("desk_code", id);
        } catch (DuplicateKeyException e) {
            jsonResult.setMsg("房间创建失败,请换房间名试试");
        }

    }

    //玩家加入房间
    private void joinDesk(String poker, JsonResult jsonResult) {
        //,,,加入:2wechat_name:Lin.wechat_code:121
        Desk desk = new Desk();
        String deskId = poker.substring(6, poker.indexOf("wechat_name:"));
        desk.setId(deskId);
        desk = deskBiz.getById(desk);
        if (Utils.isNotEmpty(desk)) {
            if (desk.getState().equals("0")) {
                Player player = new Player();
                player.setDeskId(Integer.valueOf(deskId));
                player.setWechatCode(poker.substring(poker.indexOf("wechat_code:")+12));
                Player player2 = playerBiz.getByCodeAndDesk(player);
                if (player2 !=null) {
                    jsonResult.setMsg("已加入,在桌上");
                } else {
                    String wechat_name = poker.substring(poker.indexOf("wechat_name:")+12, poker.indexOf("wechat_code:"));
                    player.setWechatName(wechat_name);
                    player.setIndebted(0-desk.getIncreasePosition());
                    player.setFaceValue(desk.getIncreasePosition());
                    player.setWinPrice(0);
                    try {
                        playerBiz.save(player, new User(1));
                        jsonResult.setMsg("欢迎玩家:"+wechat_name+" 入座 "+desk.getName());

                        List<Player>  players = playerBiz.getByDesk(player);
                        int total = players.size();
                        Set<Integer> hashSet = new HashSet<Integer>();
                        Random rm = new Random();
                        int cc = 0;
                        while (hashSet.size() != total) {
                            int a = rm.nextInt(total) + 1;
                            if (!hashSet.contains(a)) {
                                hashSet.add(a);
                                players.get(cc++).setOrderNum(a);
                            }
                        }
                        players.sort((a, b) -> Integer.compare(a.getOrderNum(), b.getOrderNum()));
                        for (Player player1 : players) {
                            playerBiz.update(player1, new User(1));
                        }
                        int currentPlayer = Integer.valueOf(players.get(0).getId());
                        desk.setBlind(currentPlayer);
                        desk.setNextPosition(currentPlayer);
                        deskBiz.update(desk, new User(1));
                    } catch (DuplicateKeyException e) {
                        jsonResult.setMsg("玩家:"+wechat_name+" 入座失败,无法加入游戏");
                    }
                }
            } else {
                jsonResult.setMsg("房间:"+desk.getName() + " 正在游戏中, 当前状态玩家无法加入游戏");
            }
        } else {
            jsonResult.setMsg("加入失败, 房间号不对, 请重试");
        }
    }

    //输光加码
    private void increasePosition(String poker, JsonResult jsonResult) {
        //,,,加码:2wechat_name:Lin.wechat_code:333
        Desk desk = new Desk();
        String deskId = poker.substring(6, poker.indexOf("wechat_name:"));
        desk.setId(deskId);
        desk = deskBiz.getById(desk);
        if (Utils.isNotEmpty(desk)) {
            if (desk.getState().equals("0")) {
                Player player = new Player();
                player.setDeskId(Integer.valueOf(deskId));
//            poker.substring(poker.indexOf("wechat_name:")+12, poker.indexOf("wechat_code:"))
                player.setWechatCode(poker.substring(poker.indexOf("wechat_code:")+12));
                Player player2 = playerBiz.getByCodeAndDesk(player);
                if (Utils.isNotEmpty(player2)) {
                    if (player2.getFaceValue() != 0) {
                        jsonResult.setMsg("当前筹码不为0, 无法加筹码");
                    } else {
                        player2.setIndebted(player2.getIndebted() - desk.getIncreasePosition());
                        player2.setFaceValue(desk.getIncreasePosition());
                        try {
                            playerBiz.update(player2, new User(1));
                            jsonResult.setMsg("玩家:"+player2.getWechatName()+" 加筹码成功, high起来.");
                        } catch (DuplicateKeyException e) {
                            jsonResult.setMsg("加码失败, 房间号不对, 请重试");
                        }
                    }
                } else {
                    jsonResult.setMsg("你未在桌上,加码无效");
                }
            } else {
                jsonResult.setMsg("房间:"+desk.getName() + " 正在游戏中, 当前状态无法加筹码");
            }
        } else {
            jsonResult.setMsg("加码失败, 房间号不对, 请重试");
        }
    }

    //发牌
    private void playCards(String poker, JsonResult jsonResult) {
        //,,,发牌:2
        Desk desk = new Desk();
        String deskId = poker.substring(6);
        desk.setId(deskId);
        desk = deskBiz.getById(desk);
        if (Utils.isNotEmpty(desk)) {
            Player player = new Player();
            player.setDeskId(Integer.valueOf(deskId));
            List<Player> players = playerBiz.getByDesk(player);
            if (Utils.isNotEmpty(players)) {
                List<Poker> pokers = createCards();
                Random random = new Random();
                int ra  = 0;
                Poker poker1 = null;
                for (Player player1 : players) {
                    ra  =random.nextInt(pokers.size()) + 1;
                    poker1 = pokers.get(ra);
                    pokers.remove(poker1);
                    player1.setPoker5(poker1.getName()+","+poker1.getColors());

                    ra  =random.nextInt(pokers.size()) + 1;
                    poker1 = pokers.get(ra);
                    pokers.remove(poker1);
                    player1.setPoker6(poker1.getName()+","+poker1.getColors());
                    playerBiz.update(player1, new User(1));
                }

                ra  = random.nextInt(pokers.size()) + 1;
                poker1 = pokers.get(ra);
                pokers.remove(poker1);
                desk.setPoker1(poker1.getName()+","+poker1.getColors());

                ra  = random.nextInt(pokers.size()) + 1;
                poker1 = pokers.get(ra);
                pokers.remove(poker1);
                desk.setPoker2(poker1.getName()+","+poker1.getColors());

                ra  = random.nextInt(pokers.size()) + 1;
                poker1 = pokers.get(ra);
                pokers.remove(poker1);
                desk.setPoker3(poker1.getName()+","+poker1.getColors());

                ra  = random.nextInt(pokers.size()) + 1;
                poker1 = pokers.get(ra);
                pokers.remove(poker1);
                desk.setPoker4(poker1.getName()+","+poker1.getColors());

                ra  = random.nextInt(pokers.size()) + 1;
                poker1 = pokers.get(ra);
                pokers.remove(poker1);
                desk.setPoker5(poker1.getName()+","+poker1.getColors());

                desk.setState("1");
                deskBiz.update(desk, new User(1));
                jsonResult.put("players", players);
                jsonResult.put("desk", desk);

            } else {
                jsonResult.setMsg("无玩家在场,无效发牌");
            }
        } else {
            jsonResult.setMsg("发牌失败, 房间号不对, 请重试");
        }
    }

    //下注
    private void bottomPour(String poker, JsonResult jsonResult) {
        //#:1jeton:1.11wechat_name:Lin.wechat_code:333 //下注
        Desk desk = new Desk();
        String deskId = poker.substring(2, poker.indexOf("jeton:"));
        desk.setId(deskId);
        desk = deskBiz.getById(desk);
        if (Utils.isNotEmpty(desk)) {
            String wechat_name = poker.substring(poker.indexOf("wechat_name:")+12, poker.indexOf("wechat_code:"));
            Player player = new Player();
            player.setDeskId(Integer.valueOf(deskId));
            player.setWechatCode(poker.substring(poker.indexOf("wechat_code:")+12));
            Player player2 = playerBiz.getByCodeAndDesk(player);
            if (player2 !=null) {
                String jetonStr = poker.substring(poker.indexOf("jeton:")+6, poker.indexOf("wechat_name:"));
                float jeton = 0;
                if(jetonStr.equalsIgnoreCase("allin") || jetonStr.equalsIgnoreCase("all in")){
                    jeton = player2.getFaceValue();
                } else if(jetonStr.equalsIgnoreCase("check")){//不下注
                    jeton = 0;
                } else if(jetonStr.equalsIgnoreCase("Call")){//跟注
                    jeton = 0;
                } else if(jetonStr.equalsIgnoreCase("fold")){//弃牌
                    jeton = 0;
                } else {
                    jeton = Math.round(Float.parseFloat(jetonStr) * 100) / 100;
                }
                if (desk.getNextPosition() == player2.getOrderNum()) {
//                    DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
//                    jeton=decimalFormat.format(jeton);//format 返回的是字符串
                    List<Player> players = playerBiz.getByDesk(player);
                    if (!(jeton >= 0 && jeton <= player2.getFaceValue())) {
                        jsonResult.setMsg("玩家:"+wechat_name+"筹码数为:"+player2.getFaceValue()+",筹码不足,请充值.");
                        return;
                    }
                    List<PlayerJeton> playerJetons = playerJetonBiz.list(new PlayerJeton(), new User(1));
                    float next_position = 1;
                    PlayerJeton playerJeton = new PlayerJeton();
                    if (Utils.isNotEmpty(playerJetons)) {
                        playerJeton = playerJetons.get(0);
                    } else {
                        playerJeton.setPlayerId(null);
                        playerJeton.setPrice(null);
                    }
                    if (playerJeton.getPrice() != null && jeton != player2.getFaceValue()) {
                        if (!(playerJeton.getPrice() == jeton && playerJeton.getPrice()*2 <= jeton)) {
                            jsonResult.setMsg("请出1倍或者2倍以上的筹码数.");
                            return;
                        }
                    }
                    boolean ret = true;
                    for (Player player1 : players) {
                        if (player1.getOrderNum() > player2.getOrderNum()) {
                            desk.setNextPosition(player1.getOrderNum());
                            ret = false;
                            break;
                        }
                    }
                    if (ret) {
                        desk.setNextPosition(1);
                    }
                    if (playerJeton.getPlayerId() != null && jeton != player2.getFaceValue()) {
                        desk.setChangeJeton(player2.getOrderNum());
                    }
                    deskBiz.update(desk, new User(1));

                    PlayerJeton playerJeton2 = new PlayerJeton();
                    playerJeton2.setPlayerId(Integer.valueOf(player2.getId()));
                    playerJeton2.setPrice(jeton);
                    playerJetonBiz.save(playerJeton2, new User(1));

                } else {
                    jsonResult.setMsg("当前下注玩家:"+wechat_name+" 还没轮到你,不能下注");
                }

            } else {
                jsonResult.setMsg("玩家:"+wechat_name+" 不在桌上,不能下注");
            }
        } else {
            jsonResult.setMsg("发牌失败, 房间号不对, 请重试");
        }
    }

    //扑克牌
    private List<Poker> createCards() {
        List<Poker> pokers = new ArrayList<>();
        String[] str = new String[]{"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        String[] colors = new String[] {"红桃", "方块", "梅花", "黑桃"};
        Poker p = null;
        for (String s : str) {
            for (int i = 0; i < 4; i++) {
                p = new Poker();
                p.setName(s);
                p.setColors(colors[i]);
                pokers.add(p);
            }
        }
        return pokers;
    }

    @Override
    public JsonResult list(PageResult2<T> page, Desk desk, User loginUser)  throws Exception{
        return deskBiz.list(page,desk,loginUser);
    }

    @Override
    public JsonResult list(Desk desk, User loginUser) {
        return JsonResult.ok().setData(deskBiz.list(desk,loginUser));
    }

    @Override
    public JsonResult getById(Desk desk) {
        return JsonResult.ok().setData(deskBiz.getById(desk));
    }

    @Transactional
    @Override
    public JsonResult save(Desk desk, User loginUser) {
        deskBiz.save(desk, loginUser);
        return JsonResult.ok("添加成功");
    }

    @Transactional
    @Override
    public JsonResult update(Desk desk, User loginUser) {
        if (deskBiz.update(desk, loginUser)) {
            return JsonResult.ok("修改成功");
        }
        return JsonResult.error("修改失败");
    }

    @Transactional
    @Override
    public JsonResult remove(Desk desk, User loginUser) {
        if (deskBiz.remove(desk, loginUser)) {
            return JsonResult.ok("删除成功");
        }
        return JsonResult.error("删除失败");
    }

}
